#ifndef MESSAGE_UTIL_H
#define MESSAGE_UTIL_H

#include <QJsonObject>
#include <QJsonDocument>
#include <QByteArray>

enum MessageType {
    PRIVATE_CHAT,
    GROUP_CHAT,
    LOGIN_REQUEST,
    REGISTER_REQUEST,
    LOGIN_RESPONSE,
    REGISTER_RESPONSE,
    ADD_FRIEND,
    REMOVE_FRIEND,
    CREATE_GROUP,
    ADD_GROUP_MEMBER,
    REMOVE_GROUP_MEMBER,
    SEND_GROUP_MESSAGE,
    GET_GROUP_MESSAGES,
    GET_FRIENDS_LIST,
    ONLINE_USERS_UPDATE,
    IMAGE_TRANSFER,      // 图片传输
    FILE_TRANSFER,       // 文件传输
    FILE_TRANSFER_RESPONSE,
    IMAGE_TRANSFER_RESPONSE
};

class MessageUtil {
public:
    // 将消息类型和JSON数据打包为传输用的QByteArray
    static QByteArray serialize(MessageType type, const QJsonObject& data) {
        QJsonObject envelope;
        envelope["type"] = static_cast<int>(type);
        envelope["data"] = data;
        //return QJsonDocument(envelope).toJson(QJsonDocument::Compact);
        QByteArray serializedData = QJsonDocument(envelope).toJson(QJsonDocument::Compact);
        serializedData.append('\n'); // 添加换行符作为结束标志
        return serializedData;
    }

    // 从QByteArray解析出消息类型和JSON数据
    static bool deserialize(const QByteArray& bytes, MessageType& outType, QJsonObject& outData) {
        QByteArray trimmedBytes = bytes;
        // 去掉可能存在的结束标志（换行符）
        if (trimmedBytes.endsWith('\n')) {
            trimmedBytes.chop(1);
        }

        QJsonParseError error;
        QJsonDocument doc = QJsonDocument::fromJson(trimmedBytes, &error);
        if (error.error != QJsonParseError::NoError) return false;
        // QJsonParseError error;
        // QJsonDocument doc = QJsonDocument::fromJson(bytes, &error);
        // if (error.error != QJsonParseError::NoError) return false;

        QJsonObject envelope = doc.object();
        if (!envelope.contains("type") || !envelope["type"].isDouble()) return false;
        if (!envelope.contains("data") || !envelope["data"].isObject()) return false;

        int typeInt = envelope["type"].toInt();
        //qDebug()<<typeInt;
        //if (typeInt < PRIVATE_CHAT || typeInt > REGISTER_RESPONSE) return false;

        outType = static_cast<MessageType>(typeInt);
        outData = envelope["data"].toObject();
        return true;
    }

    //----- 针对不同消息类型的快捷构造方法 -----

    // 示例1：构建登录请求消息
    static QByteArray buildLoginRequest(const QString& username, const QString& password) {
        QJsonObject data;
        data["username"] = username;
        data["password"] = password;
        return serialize(LOGIN_REQUEST, data);
    }

    // 示例2：解析登录响应
    static bool parseLoginResponse(const QJsonObject& data, bool& success, QString& token) {
        if (!data.contains("success") || !data["success"].isBool()) return false;
        if (!data.contains("token") || !data["token"].isString()) return false;

        success = data["success"].toBool();
        token = data["token"].toString();
        return true;
    }

    // 示例3：构建私聊消息
    static QByteArray buildPrivateChat(
        const QString& sender,
        const QString& receiver,
        const QString& text
        ) {
        QJsonObject data;
        data["sender"] = sender;
        data["receiver"] = receiver;
        data["text"] = text;
        data["timestamp"] = QDateTime::currentMSecsSinceEpoch();
        return serialize(PRIVATE_CHAT, data);
    }
    // 图片传输
    static QByteArray buildImageTransfer(
        const QString& sender,
        const QString& receiver,
        const QByteArray& imageData,
        const QString& imageName
        ) {
        QJsonObject data;
        data["sender"] = sender;
        data["receiver"] = receiver;
        data["fileName"] = imageName;
        data["fileData"] = QString(imageData.toBase64());
        return serialize(IMAGE_TRANSFER, data);
    }

    // 文件传输
    static QByteArray buildFileTransfer(
        const QString& sender,
        const QString& receiver,
        const QByteArray& fileData,
        const QString& fileName
        ) {
        QJsonObject data;
        data["sender"] = sender;
        data["receiver"] = receiver;
        data["fileName"] = fileName;
        data["fileData"] = QString(fileData.toBase64());
        return serialize(FILE_TRANSFER, data);
    }
};


#endif // MESSAGE_UTIL_H
